//
//  LEEHomeTableController.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/12.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel


private let LEEStatuseCell_ID = "LEEStatuseCell_ID"
private let LEERetweetedCell_ID = "LEERetweetedCell_ID"

let orginalCell = UINib(nibName: "LEEStatuseCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! LEEStatuseCell
let retweetedCell = UINib(nibName: "LEERetweetedCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! LEEStatuseCell

class LEEHomeTableController: LEEBasicTableController {
    
    lazy var needLoadArray: [IndexPath] = [IndexPath]()

    let statusesViewModel = LEEWeiboStatusesViewModel()
    
    let refreshView = LEERefreshView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        JPFPSStatus.sharedInstance().open()

        //判断是否首次登录。否者一开始加载数据失败
        if !isLoagin {
            
            visitorView.updateInfo(title: "我是首页我是首页我是首页我是首页我是首页我是首页我是首页", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            
            
            return
        }
        navItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", taget: self, action: #selector(saoyisao))
        
        loadingData()
        //设置tableview
        setupTableView()
    }
    
    func loadingData() {
        //防止用户不停的向下拉刷新
//        if (self.tableView.refreshControl?.isRefreshing == true) {
//            return
//        }
        
        //加载数据，闭包回调 ,通过下面小菊花是否转动判断是否上拉
        statusesViewModel.loadData(isPullup: indicator.isAnimating) { (isSuccess, count) in
            if !isSuccess {
                SVProgressHUD.showError(withStatus: "网络加载错误,请检查网络哦")
                self.refreshView.endRefresh()
                return
            }
            if !self.indicator.isAnimating {
            
                self.setAnimation(count: count)
            }
            
            //下拉加载数据完毕后
//            self.tableView.refreshControl?.endRefreshing()
            self.refreshView.endRefresh()
            
            //上拉加载数据完毕后
            self.indicator.stopAnimating()
            self.tableView.reloadData()
        }
        
    }
    
    /// //设置tableview
    private func setupTableView() {
    
        //原创微博
        let nib = UINib(nibName: "LEEStatuseCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: LEEStatuseCell_ID)
        
        //转发微博
        let nib2 = UINib(nibName: "LEERetweetedCell", bundle: nil)
        tableView.register(nib2, forCellReuseIdentifier: LEERetweetedCell_ID)
        
        //分割线
        tableView.separatorStyle = .none
        
        tableView.tableFooterView = indicator
        
        //下拉刷新
//        tableView.refreshControl = UIRefreshControl()
//        tableView.refreshControl?.addTarget(self, action: #selector(loadingData), for: .valueChanged)

        refreshView.addTarget(self, action: #selector(loadingData), for: .valueChanged)
        tableView.addSubview(refreshView)
        
        view.insertSubview(successLbl, belowSubview: navBar)
    }
    
    //设置动画
    func setAnimation(count : Int) {
        if !successLbl.isHidden  {
            return
        }
        
        if count == 0 {
            successLbl.text = "已经是最新的微博"
        }else{
        
            successLbl.text = "更新了\(count)条微博"
        }
        
        successLbl.isHidden = false
        
        UIView.animate(withDuration: 1, animations: {
            
            self.successLbl.frame.origin.y = navBarH
            
        }) { (_) in
           
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                
                self.successLbl.frame.origin.y = navBarH - 34
                
            }, completion: { (_) in
                
                self.successLbl.isHidden = true
            })
            
            
        }
        
    }
    //懒加载successLbl 
    private lazy var successLbl: UILabel = {
        let successLbl = UILabel(title: "", textColor: UIColor.white, font: 14)
        successLbl.backgroundColor = UIColor.orange
        successLbl.frame = CGRect(x: 0, y: navBarH - 34, width: kUISCRRENW, height: 34)
        
        successLbl.isHidden = true
        return successLbl
    }()
    
    ///向上拉 小菊花
     lazy var indicator: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
        
        indicator.color = UIColor.red
        return indicator
    }()
    
    @objc private func saoyisao() {
    
    navigationController?.pushViewController(LEETestController(), animated: true)
    }

}

extension LEEHomeTableController {

    // MARK: - Table view data source
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusesViewModel.arrayStatuses.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = statusesViewModel.arrayStatuses[indexPath.row]
        
        var cell_ID = LEEStatuseCell_ID
        
        if model.statuse?.retweeted_status != nil {
            
            cell_ID = LEERetweetedCell_ID
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cell_ID, for: indexPath) as! LEEStatuseCell
        
        
        //如果需要加载的数组的数量大于0 并且 正要加载的indexPath不在按需加载的数组中 就不渲染cell
        if needLoadArray.count > 0 {
            let result = needLoadArray.contains(where: { (index) -> Bool in
                return index.row == indexPath.row && index.section == indexPath.section
            })
            
            if !result {
                print("^    😈😈😈😈😈😈😈打酱油😈😈😈😈😈😈")
                return cell
            }
        }
        
        cell.itemModel = model
        
        cell.selectionStyle = .none
        return cell
    }
    
    //如果在这里完成自定刷新控件UI的更新, 这就是强耦合
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let ip = tableView.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        guard let cip = tableView.indexPathsForVisibleRows?.first else {
            return
        }
        
        let skipCount = 12;
        
        if labs(cip.row - ip.row) > skipCount {
            guard let temp = tableView.indexPathsForRows(in: CGRect(x: 0, y: targetContentOffset.pointee.y, width: self.view.frame.width, height: self.view.frame.height)) else {
                
                return
            }
            var arr = temp
            print(velocity.y)
            //向下滑动
            if velocity.y < 0 {
                
                let indexPath = temp.last!
                if (indexPath.row + 3 < self.statusesViewModel.arrayStatuses.count) {
                    arr.append(IndexPath(row: indexPath.row + 1, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 3, section: 0))
                }
            }else{
                //向上滑动
                let indexPath = temp.first!
                if (indexPath.row > 3) {
                    arr.append(IndexPath(row: indexPath.row - 3, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 1, section: 0))
                }
            }
            needLoadArray.append(contentsOf: arr)
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = statusesViewModel.arrayStatuses[indexPath.row]
        
        //由于tableView要显示先调用获取行高的方法  -> 在行高的方法内部会获取缓存的cell  -> dequeueReusableCell: indexPath内部会调用 heightForRowAt: --> 形成递归调用
        //获取cell的时候就不能够使用 dequeueReusableCell: indexPath
        //使用NSBundle的方式加载cell文件']\
//        let cell = UINib(nibName: nibName(model : model), bundle: nil).instantiate(withOwner: nil, options: nil).last as! LEEStatuseCell
        //要绑定数据啊！！！
//        let cell = loadCell(model: model)
        
//        cell.itemModel = model
//        cell.layoutIfNeeded()
        
        return model.rowHeight
    }
    
        //往上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        //倒数第2个开始刷新
        if indicator.isAnimating == false && indexPath.row == statusesViewModel.arrayStatuses.count - 2 {
            
            indicator.startAnimating()
            
            self.loadingData()
        }
        
    }
    

}




